/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.unifor.sd.bolsa.rmi;

import br.unifor.sd.bolsa.interfaces.ClienteInterface;
import br.unifor.sd.bolsa.interfaces.ListListener;
import br.unifor.sd.bolsa.util.Acao;
import br.unifor.sd.bolsa.util.Dialeto;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Pedro
 */
public class ClienteImplRMI implements ClienteInterface, ListListener {
    
    private ServidorRemote stub;
    private List<ListListener> listeners;
    private String nome;
    private ClienteRemote skeletor;

    public ClienteImplRMI(){
        listeners = new ArrayList<ListListener>();
    }

    public void conectar(String ip, Integer porta) throws Exception {
        Registry registry = LocateRegistry.getRegistry(ip, porta);
        stub = (ServidorRemote) registry.lookup("Bolsa");        
        skeletor = new ClienteRemoteImpl();
        Registry registryClient = LocateRegistry.createRegistry(Dialeto.randomPort(100, 200));
        registryClient.bind("Cliente", skeletor);
        //skeletor.addListener(this);

    }

    public void encerrarConexao() throws Exception {
        
    }

    public void escutar() {
        
    }

    public void addListener(ListListener listener) {
        listeners.add(listener);
    }

    public void iniciar() throws Exception {
        stub.iniciar(skeletor);
    }

    public void comprarAcao(Integer acaoId) throws Exception {
        
    }

    public void comprarAcaoValor(Integer acaoId, Double valor) throws Exception {
        System.out.println("teste");
        stub.comprarAcao(acaoId, "", valor);
    }

    public void venderAcao(Integer acaoId) throws Exception {
        
    }

    public void setDono(String dono) {
        this.nome = dono;
    }

    public void message(List<Acao> lista) {
        for (int i = 0; i < listeners.size(); i++) {
            listeners.get(i).onMessage(lista);
        }
    }

    public void onMessage(List<Acao> lista) {
        message(lista);
    }

}
